;kmeans classifier
;input is an m,n array where m is number of attribs and n is number of instances
;ditto for seeds
function kmeans, input, seeds, max_distance, max_iterations, final_seeds=final_seeds, last_means=last_means
	;setup
	sz = size(input, /dimensions)
	nclasses = n_elements(seeds[0,*])

	;find classes
	assigned_clusters = min_dist(input, seeds, max_distance ^ 2, distances=rawdist)
	;rawdist = sqrt(rawdist)
	;for each class measure mean distance from class centriod to all classified instances
	;record so can be passed to next iteration
	means = seeds
	for i=0L, nclasses - 1 do begin
		cinstances = where(assigned_clusters eq i)
		if (cinstances[0] ne -1) then for k=0L, sz[0] - 1 do begin
			means[k,i] = mean(input[k,cinstances])
		endfor
	endfor
	;move centriods to mean of classified instances
	;new_seeds = means

	;repeat or terminate
	if ((max_iterations lt 2) || (arg_present(last_means) && array_equal(last_means, means))) then begin
		if (arg_present(final_seeds)) then final_seeds=means
		return, assigned_clusters
	endif
	return, kmeans(input, means, max_distance, max_iterations - 1, final_seeds=final_seeds, last_means=seeds)
end



pro testkmeans
	tinp = [[1,1,1],$
			[2,2,2],$
			[3,3,3],$
			[4,4,4],$
			[5,5,5]]

	tseed = [[6,6,6],$
			[7,7,7]]
	res = distanceperseed( tinp, tseed)
	help,res
	print, sqrt(res)
end